
package com.be.beadmin.product.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.dto.input.WorkHoursRequestHstByStatePage;
import com.be.beadmin.product.dto.input.WorkHoursRequestHstByTaskIdPage;
import com.be.beadmin.product.dto.input.WorkHoursRequestHstDto;
import com.be.beadmin.product.dto.output.WorkHoursRequestHstEx;
import com.be.beadmin.product.entity.*;
import com.be.beadmin.product.mapper.WorkHoursRequestHstMapper;
import com.be.beadmin.product.mapper.WorkHoursRequestHstMapperEx;
import com.be.beadmin.product.repository.PlantCapacityCalendarRepository;
import com.be.beadmin.product.repository.ProductManufactInforRepository;
import com.be.beadmin.product.repository.WorkHoursRequestHstRepository;
import com.be.beadmin.product.service.PlantCapacityCalendarService;
import com.be.beadmin.product.service.WorkHoursRequestHstService;
import com.be.beadmin.product.service.WorkingHoursCountService;
import com.be.beadmin.product.task.WorkingHoursCountTask;
import com.be.beadmin.project.entity.BatchProduct;
import com.be.beadmin.project.repository.BatchProductRepository;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import com.be.beadmin.service.task.BaseTask;
import com.be.beadmin.service.task.TaskThreadPool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @description 服务实现
* @author ljh
* @date 2023-04-18
**/
@Service
@RequiredArgsConstructor
public class WorkHoursRequestHstServiceImpl implements WorkHoursRequestHstService {

    @Autowired
    private  WorkHoursRequestHstRepository workHoursRequestHstRepository;
    @Autowired
    private  WorkHoursRequestHstMapper workHoursRequestHstMapper;
    @Autowired
    private  WorkHoursRequestHstMapperEx workHoursRequestHstExMapper;

    @Autowired
    private ProductManufactInforRepository productManufactInforRepository;

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;


    @Autowired
    private TaskThreadPool taskThreadPool;


    @Autowired
    private WorkingHoursCountService workingHoursCountService;
    @Autowired
    private NotifyInfoRepository notifyInfoRepository;

    @Autowired
    private PlantCapacityCalendarRepository plantCapacityCalendarRepository;

    @Autowired
    private BatchProductRepository batchProductRepository;


    @Autowired
    private PlantCapacityCalendarService plantCapacityCalendarService;

    @Override
    public Page<WorkHoursRequestHstEx> getWorkHoursRequestHstByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<WorkHoursRequestHst> page = workHoursRequestHstRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkHoursRequestHst_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkHoursRequestHst_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<WorkHoursRequestHstEx> page1 = page.map(workHoursRequestHstExMapper::toEntity);
            return page1;
    }

    @Override
    public Page<WorkHoursRequestHstEx> getWorkHoursRequestHstByPageAndTaskId(WorkHoursRequestHstByTaskIdPage workHoursRequestHstByTaskIdPage) {
        PageEntity pageEntity = workHoursRequestHstByTaskIdPage.getPageEntity();
        String taskId = workHoursRequestHstByTaskIdPage.getTaskId();
        if (taskId == null) throw new BeadminException("需要指定生产工序id");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<WorkHoursRequestHst> page = workHoursRequestHstRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkHoursRequestHst_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(WorkHoursRequestHst_.taskId), taskId); //过滤为taskId
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkHoursRequestHst_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<WorkHoursRequestHstEx> page1 = page.map(workHoursRequestHstExMapper::toEntity);
        return page1;
    }

    @Override
    public Page<WorkHoursRequestHstEx> getWorkHoursRequestHstByPageAndState(WorkHoursRequestHstByStatePage workHoursRequestHstByStatePage) {
        PageEntity pageEntity = workHoursRequestHstByStatePage.getPageEntity();
        String state = workHoursRequestHstByStatePage.getState();
        if (state == null) throw new BeadminException("需要指定审批状态");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<WorkHoursRequestHst> page = workHoursRequestHstRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkHoursRequestHst_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(WorkHoursRequestHst_.status),state ); //过滤为taskId
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkHoursRequestHst_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<WorkHoursRequestHstEx> page1 = page.map(workHoursRequestHstExMapper::toEntity);
        return page1;
    }

    @Override
    public void addWorkHoursRequestHst(WorkHoursRequestHstDto workHoursRequestHstDto) {
            WorkHoursRequestHst result = workHoursRequestHstRepository.findWorkHoursRequestHstByIdAndDelete(workHoursRequestHstDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("WorkHoursRequestHst不存在,请重新查询");
            }
            WorkHoursRequestHst workHoursRequestHst = workHoursRequestHstMapper.toEntity(workHoursRequestHstDto);
            workHoursRequestHstRepository.save(workHoursRequestHst);
    }

    @Transactional
    @Override
    public void updateWorkHoursRequestHst(WorkHoursRequestHstDto workHoursRequestHstDto) {
            WorkHoursRequestHst workHoursRequestHst=workHoursRequestHstRepository.save(workHoursRequestHstMapper.toEntity(workHoursRequestHstDto));
            int status = workHoursRequestHstDto.getStatus();
            int requestType = workHoursRequestHstDto.getRequestType();
            if(status == 2){//审核通过

                if(requestType==0){
                    //工单工时审核

//                    补录工时累加到工时统计的实际工单填报工时


                    //-----------------------------------------------------------------------
                    // 审批人 发送 工时补录 通知给  填报人
                    NotifyInfo notifyInfo =new NotifyInfo();
                    notifyInfo.setModuleName("生产制造");
                    notifyInfo.setFuncName("工单工时审核");
                    notifyInfo.setNotifyDesc("项目号为["+workHoursRequestHst.getProjectName()+"],工单号为["+workHoursRequestHst.getWo()+"],工序为["+workHoursRequestHst.getProcessName()+"]--工单工时补录申请审核通过");
                    notifyInfo.setNotifyType("通知");
                    notifyInfo.setSenderName(workHoursRequestHst.getOperator());
                    notifyInfo.setSendTime(workHoursRequestHst.getUpdateTime());
                    notifyInfo.setSenderId(workHoursRequestHst.getApproveManId());
                    String receiver = workHoursRequestHst.getRequestManId();

                    notifyInfo = notifyInfoRepository.save(notifyInfo);

                    notifyTemplateInfoService.sendNotify(notifyInfo,-1,workHoursRequestHst.getRequestMan(),receiver);
                }else if(requestType==1){
                    //项目工时审核


                    //补录工时累加到工时统计的实际项目填报工时


                    //-----------------------------------------------------------------------
                    // 审批人 发送 工时补录 通知给  填报人
                    NotifyInfo notifyInfo =new NotifyInfo();
                    notifyInfo.setModuleName("生产制造");
                    notifyInfo.setFuncName("项目工时审核");
                    String res;
                    notifyInfo.setNotifyDesc("项目号为["+workHoursRequestHst.getProjectCode()+"],填报人为["+workHoursRequestHst.getRequestMan()+"]--项目工时填报申请审核用过");
                    notifyInfo.setNotifyType("通知");
                    notifyInfo.setSenderName(workHoursRequestHst.getOperator());
                    notifyInfo.setSendTime(workHoursRequestHst.getUpdateTime());
                    notifyInfo.setSenderId(workHoursRequestHst.getApproveManId());
                    String receiver = workHoursRequestHst.getRequestManId();
                    // 工时审核没有 用户id字段，用的用户名
                    notifyInfo = notifyInfoRepository.save(notifyInfo);

                    notifyTemplateInfoService.sendNotify(notifyInfo,-1,workHoursRequestHst.getRequestMan(),receiver);

                }
                WorkingHoursCountTask workingHoursCountTask = new WorkingHoursCountTask();
                taskThreadPool.execute(workingHoursCountTask);
            }else if(status == -1){
                // 驳回
                if(requestType==0){
                    //工单工时补录
                    //-----------------------------------------------------------------------
                    // 审批人 发送 工时补录 通知给  填报人
                    NotifyInfo notifyInfo =new NotifyInfo();
                    notifyInfo.setModuleName("生产制造");
                    notifyInfo.setFuncName("工时审核");
                    notifyInfo.setNotifyDesc("工单号为["+workHoursRequestHst.getWo()+"],工序为["+workHoursRequestHst.getProcessName()+"]--工时补录申请审核驳回");
                    notifyInfo.setNotifyType("通知");
                    notifyInfo.setSenderName(workHoursRequestHst.getOperator());
                    notifyInfo.setSendTime(workHoursRequestHst.getUpdateTime());
                    notifyInfo.setSenderId(workHoursRequestHst.getApproveManId());
                    String receiver = workHoursRequestHst.getRequestManId();
                    // 工时审核没有 用户id字段，用的用户名
                    notifyInfo = notifyInfoRepository.save(notifyInfo);

                    notifyTemplateInfoService.sendNotify(notifyInfo,-1,workHoursRequestHst.getRequestMan(),receiver);
                }else if(requestType==1){
                    //项目工时填报
                    //-----------------------------------------------------------------------
                    // 审批人 发送 工时补录 通知给  填报人
                    NotifyInfo notifyInfo =new NotifyInfo();
                    notifyInfo.setModuleName("生产制造");
                    notifyInfo.setFuncName("工时审核");
                    notifyInfo.setNotifyDesc("项目号为["+workHoursRequestHst.getProjectCode()+"],填报人为["+workHoursRequestHst.getRequestMan()+"]--项目工时填报申请审核驳回");
                    notifyInfo.setNotifyType("通知");
                    notifyInfo.setSenderName(workHoursRequestHst.getOperator());
                    notifyInfo.setSendTime(workHoursRequestHst.getUpdateTime());
                    notifyInfo.setSenderId(workHoursRequestHst.getApproveManId());
                    String receiver = workHoursRequestHst.getRequestManId();
                    // 工时审核没有 用户id字段，用的用户名
                    notifyInfo = notifyInfoRepository.save(notifyInfo);

                    notifyTemplateInfoService.sendNotify(notifyInfo,-1,workHoursRequestHst.getRequestMan(),receiver);
                }

            }

    }


    @Override
    public void delWorkHoursRequestHst(String id) {
        WorkHoursRequestHst workHoursRequestHst = workHoursRequestHstRepository.findWorkHoursRequestHstById(id);
        workHoursRequestHst.setDelete(1);
        workHoursRequestHstRepository.save(workHoursRequestHst);
    }

    @Override
    public void delWorkHoursRequestHsts (List<String> ids) { }
}